package com.plugin.manage.controller;

import com.plugin.core.bean.LogAop;
import com.plugin.core.model.entity.SysMenu;
import com.plugin.core.model.entity.SysRole;
import com.plugin.manage.common.PageResult;
import com.plugin.manage.common.RespObj;
import com.plugin.manage.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public RespObj<?> get() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Long userId = (Long)authentication.getPrincipal();
            Long roleId = (Long)authentication.getCredentials();

            // 参数验证
            if (userId == null || roleId == null) {
                return new RespObj<>().error("用户ID或角色ID不能为空");
            }

            // 使用新的服务方法查询角色
            SysRole role = sysRoleService.getRoleByUserIdAndRoleId(userId, roleId);
            return new RespObj<>().success(role);

        } catch (Exception e) {
            return new RespObj<>().error("查询角色失败：" + e.getMessage());
        }
    }


    /**
     * 新增
     * @return
     */
    @RequestMapping("/add")
    @LogAop( remark = "新增角色" )
    @ResponseBody
    public RespObj<?> add(@RequestBody SysRole sysRole) {
        try {
            Long roleId = sysRoleService.addRole(sysRole);
            return new RespObj<>().success(roleId);

        } catch (Exception e) {
            return new RespObj<>().error("新增角色失败：" + e.getMessage());
        }
    }

    /**
     * 修改
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    @LogAop( remark = "修改角色" )
    public RespObj<?> update(@RequestBody SysRole sysRole) {
        try {
            boolean success = sysRoleService.updateRole(sysRole);
            if (success) {
                return new RespObj<>().success("修改角色成功");
            } else {
                return new RespObj<>().error("修改角色失败");
            }

        } catch (Exception e) {
            return new RespObj<>().error("修改角色失败：" + e.getMessage());
        }
    }

    /**
     * 列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public RespObj<?> list(@RequestParam(defaultValue = "1") int pageIndex,
                           @RequestParam(defaultValue = "10") int pageSize,
                           @RequestParam(required = false) String roleName,
                           @RequestParam(required = false) String roleKey,
                           @RequestParam(required = false) String status) {
        try {
            // 构建查询条件
            SysRole queryRole = new SysRole();
            if (org.springframework.util.StringUtils.hasText(roleName)) {
                queryRole.setRoleName(roleName);
            }
            if (org.springframework.util.StringUtils.hasText(roleKey)) {
                queryRole.setRoleKey(roleKey);
            }
            if (org.springframework.util.StringUtils.hasText(status)) {
                queryRole.setStatus(status);
            }

            // 计算偏移量
            int offset = (pageIndex - 1) * pageSize;

            // 查询角色列表
            List<SysRole> roleListResult = sysRoleService.getRoleList(offset, pageSize, queryRole);

            // 查询总数
            Integer countResult = sysRoleService.countRoles(queryRole);

            // 构建分页结果
            return new RespObj<>().success(new PageResult<>(roleListResult, countResult));

        } catch (Exception e) {
            return new RespObj<>().error("查询角色列表失败：" + e.getMessage());
        }
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @LogAop( remark = "删除角色" )
    public RespObj<?> delete(@RequestParam String roleIds) {
        try {
            if (!org.springframework.util.StringUtils.hasText(roleIds)) {
                return new RespObj<>().error("角色ID不能为空");
            }

            String[] idArray = roleIds.split(",");
            int successCount = sysRoleService.batchDeleteRoles(
                Arrays.stream(idArray).map(Long::valueOf).toArray(Long[]::new)
            );

            return new RespObj<>().success("成功删除" + successCount + "个角色");

        } catch (Exception e) {
            return new RespObj<>().error("删除角色失败：" + e.getMessage());
        }
    }

    /**
     * 所有角色列表
     * @return
     */
    @RequestMapping("/all")
    @ResponseBody
    public RespObj<?> all() {
        try {
            List<SysRole> roles = sysRoleService.getAllRoles();
            return new RespObj<>().success(roles);

        } catch (Exception e) {
            return new RespObj<>().error("查询所有角色失败：" + e.getMessage());
        }
    }

    /**
     * 查看角色所有资源
     * @param roleId 角色ID
     * @return
     */
    @RequestMapping("/permission_view")
    @ResponseBody
    public RespObj<?> viewPermission(@RequestParam Long roleId) {
        try {
            if (roleId == null) {
                return new RespObj<>().error("角色ID不能为空");
            }

            List<SysMenu> permissions = sysRoleService.getRolePermissions(roleId);
            return new RespObj<>().success(permissions);

        } catch (Exception e) {
            return new RespObj<>().error("查询角色权限失败：" + e.getMessage());
        }
    }

    /**
     * 保存角色的资源权限
     * @param roleId 角色ID
     * @param menuIds 菜单ID列表
     * @return
     */
    @RequestMapping("/permission_save")
    @ResponseBody
    @LogAop(remark = "角色分配权限")
    public RespObj<?> savePermission(@RequestParam Long roleId, @RequestParam String menuIds) {
        try {
            if (roleId == null) {
                return new RespObj<>().error("角色ID不能为空");
            }

            boolean success = sysRoleService.saveRolePermissions(roleId, menuIds);
            if (success) {
                return new RespObj<>().success("保存角色权限成功");
            } else {
                return new RespObj<>().error("保存角色权限失败");
            }

        } catch (Exception e) {
            return new RespObj<>().error("保存角色权限失败：" + e.getMessage());
        }
    }

    /**
     * 角色状态修改
     * @param roleId 角色ID
     * @param status 状态
     * @return
     */
    @RequestMapping("/change_status")
    @ResponseBody
    @LogAop(remark = "修改角色状态")
    public RespObj<?> changeStatus(@RequestParam Long roleId, @RequestParam String status) {
        try {
            if (roleId == null) {
                return new RespObj<>().error("角色ID不能为空");
            }

            SysRole sysRole = new SysRole();
            sysRole.setRoleId(roleId);
            sysRole.setStatus(status);

            boolean success = sysRoleService.updateRole(sysRole);
            if (success) {
                return new RespObj<>().success("修改角色状态成功");
            } else {
                return new RespObj<>().error("修改角色状态失败");
            }

        } catch (Exception e) {
            return new RespObj<>().error("修改角色状态失败：" + e.getMessage());
        }
    }

    /**
     * 检查角色名称是否唯一
     * @param roleName 角色名称
     * @param roleId 角色ID（编辑时传入，新增时不传）
     * @return
     */
    @RequestMapping("/check_role_name")
    @ResponseBody
    public RespObj<?> checkRoleName(@RequestParam String roleName, 
                                   @RequestParam(required = false) Long roleId) {
        try {
            if (!org.springframework.util.StringUtils.hasText(roleName)) {
                return new RespObj<>().error("角色名称不能为空");
            }

            boolean exists = sysRoleService.checkRoleNameExists(roleName, roleId);
            return new RespObj<>().success(!exists);

        } catch (Exception e) {
            return new RespObj<>().error("检查角色名称失败：" + e.getMessage());
        }
    }

    /**
     * 检查角色标识是否唯一
     * @param roleKey 角色标识
     * @param roleId 角色ID（编辑时传入，新增时不传）
     * @return
     */
    @RequestMapping("/check_role_key")
    @ResponseBody
    public RespObj<?> checkRoleKey(@RequestParam String roleKey, 
                                  @RequestParam(required = false) Long roleId) {
        try {
            if (!org.springframework.util.StringUtils.hasText(roleKey)) {
                return new RespObj<>().error("角色标识不能为空");
            }

            boolean exists = sysRoleService.checkRoleKeyExists(roleKey, roleId);
            return new RespObj<>().success(!exists);

        } catch (Exception e) {
            return new RespObj<>().error("检查角色标识失败：" + e.getMessage());
        }
    }

    /**
     * 获取角色详细信息
     * @param roleId 角色ID
     * @return
     */
    @RequestMapping("/detail")
    @ResponseBody
    public RespObj<?> detail(@RequestParam Long roleId) {
        try {
            if (roleId == null) {
                return new RespObj<>().error("角色ID不能为空");
            }

            SysRole role = sysRoleService.getRoleById(roleId);
            return new RespObj<>().success(role);

        } catch (Exception e) {
            return new RespObj<>().error("获取角色详情失败：" + e.getMessage());
        }
    }

    /**
     * 导出角色列表
     * @param roleName 角色名称
     * @param roleKey 角色标识
     * @param status 状态
     * @return
     */
    @RequestMapping("/export")
    @ResponseBody
    @LogAop(remark = "导出角色数据")
    public RespObj<?> export(@RequestParam(required = false) String roleName,
                            @RequestParam(required = false) String roleKey,
                            @RequestParam(required = false) String status) {
        try {
            // 构建查询条件
            SysRole queryRole = new SysRole();
            if (org.springframework.util.StringUtils.hasText(roleName)) {
                queryRole.setRoleName(roleName);
            }
            if (org.springframework.util.StringUtils.hasText(roleKey)) {
                queryRole.setRoleKey(roleKey);
            }
            if (org.springframework.util.StringUtils.hasText(status)) {
                queryRole.setStatus(status);
            }

            List<SysRole> roles = sysRoleService.exportRoles(queryRole);
            return new RespObj<>().success(roles);

        } catch (Exception e) {
            return new RespObj<>().error("导出角色数据失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除角色
     * @param roleIds 角色ID数组
     * @return
     */
    @RequestMapping("/batch_delete")
    @ResponseBody
    @LogAop(remark = "批量删除角色")
    public RespObj<?> batchDelete(@RequestParam Long[] roleIds) {
        try {
            if (roleIds == null || roleIds.length == 0) {
                return new RespObj<>().error("请选择要删除的角色");
            }

            int successCount = sysRoleService.batchDeleteRoles(roleIds);
            return new RespObj<>().success("成功删除" + successCount + "个角色");

        } catch (Exception e) {
            return new RespObj<>().error("批量删除角色失败：" + e.getMessage());
        }
    }

    /**
     * 获取角色选择列表（用于下拉框等）
     * @return
     */
    @RequestMapping("/select_list")
    @ResponseBody
    public RespObj<?> selectList() {
        try {
            List<SysRole> roles = sysRoleService.getRoleSelectList();
            return new RespObj<>().success(roles);

        } catch (Exception e) {
            return new RespObj<>().error("获取角色选择列表失败：" + e.getMessage());
        }
    }
}
